package com.cat.gridChart;

/**
 * @author 曲大人的喵
 * @description https://leetcode.cn/problems/number-of-enclaves/
 * @create 2025/9/6 22:21
 * @since JDK17
 */

public class Solution08 {
    int ans, n, m;
    int[][] g;

    int dfs(int x, int y) {
        if (x == 0 || x == n - 1 || y == 0 || y == m - 1) {
            return -999999;
        }
        if (g[x][y] == 0) {
            return 0;
        }
        g[x][y] = 0;
        int ans = 1;
        if (g[x - 1][y] != 0) {
            ans += dfs(x - 1, y);
        }
        if (g[x + 1][y] != 0) {
            ans += dfs(x + 1, y);
        }
        if (g[x][y - 1] != 0) {
            ans += dfs(x, y - 1);
        }
        if (g[x][y + 1] != 0) {
            ans += dfs(x, y + 1);
        }
        return ans;
    }

    public int numEnclaves(int[][] grid) {
        n = grid.length;
        m = grid[0].length;
        g = grid;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (grid[i][j] != 0) {
                    ans += Math.max(0, dfs(i, j));
                }
            }
        }
        return ans;
    }
}
